﻿using System;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

namespace TLSC.utils
{
    public class XmlUtil
    {

        public static T Load<T>(string filePath)
        {
            T t = default(T);
            XmlTextReader reader = null;
            try
            {
                if (File.Exists(filePath))
                {
                    using (reader = new XmlTextReader(filePath))
                    {
                        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                        t = (T)xmlSerializer.Deserialize(reader);
                    }
                }
                else
                {
                    return t;
                }

                return t;
            }
            catch (Exception e)
            {
                return t;
            }
            finally
            {
                if(reader != null)
                {
                    reader.Close();
                }
            }

        }

        public static bool Save<T>(string filePath, T entity)
        {
            XmlTextWriter writer = null;
            try
            {
                int index = filePath.LastIndexOf('\\');
                string dir = filePath.Substring(0, index);
                
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                //if (File.Exists(filePath))
                //{
                using (writer = new XmlTextWriter(filePath, Encoding.Unicode))
                {
                    writer.Formatting = Formatting.Indented;
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                    xmlSerializer.Serialize(writer, entity);
                    writer.Close();
                }
                //}
                //    else
                //    {
                //    MessageBox.Show(String.Format("配置文件加载失败！路径：{0}", filePath));
                //}

                return true;
            }
            catch (Exception e)
            {
                return false;
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }
    }
}
